package com.dk.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dk.entity.TAdmin;
import com.dk.exception.LoginException;
import com.dk.mapper.TAdminMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class LoginRealm extends AuthorizingRealm {
    @Autowired
    private TAdminMapper adminMapper;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行授权方法");
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.like("username", token.getUsername());
        List<TAdmin> list = adminMapper.selectList(queryWrapper);
        TAdmin admin = list.get(0);
        if (admin.getStatus().equals(2)){
            throw new LoginException("账号异常");
        }
        return new SimpleAuthenticationInfo(admin,admin.getPassword(),ByteSource.Util.bytes(admin.getSalt()),admin.getUsername());
    }
}
